import traceback

from PyQt5.QtWidgets import (
    QMainWindow, QMessageBox, QStackedWidget
)

from back_rehabsystem import RehabSystem
from back_user import AuthManager
from front_rolebord import RoleBasedDashboard  # 新增导入
from front_window import LoginWindow, RegisterWindow, ChangePasswordWindow


class MainApp(QMainWindow):
    def __init__(self):
        super().__init__()
        # 初始化系统核心组件
        self.rehab_system = RehabSystem()  # 先创建 RehabSystem 实例
        self.auth_manager = AuthManager(backend=self.rehab_system)  # 传入 backend 参数
        # 初始化界面堆栈
        self.stacked_widget = QStackedWidget()
        self.login_window = LoginWindow(self.auth_manager, self.stacked_widget)
        # 初始化窗口
        self.login_window = LoginWindow(self.auth_manager, self.stacked_widget)
        self.register_window = RegisterWindow(self.auth_manager, self.stacked_widget)
        self.password_window = ChangePasswordWindow(self.auth_manager, self.stacked_widget)
        # 添加窗口到堆栈
        self.stacked_widget.addWidget(self.login_window)
        self.stacked_widget.addWidget(self.register_window)
        self.stacked_widget.addWidget(self.password_window)
        # 主窗口设置
        self.setCentralWidget(self.stacked_widget)
        self.setWindowTitle("医疗康复系统")
        self.setGeometry(300, 300, 800, 800)

    def show_main_menu(self, user_info):
        """登录成功后跳转到主界面（增强版）"""
        try:
            # 确保user_info是字典格式
            if isinstance(user_info, tuple) and len(user_info) == 2:
                success, data = user_info
                if not success:
                    raise ValueError("登录失败")
                user_info = data
            if not isinstance(user_info, dict):
                raise ValueError("无效的用户信息格式")
            # 创建主界面
            self.dashboard = RoleBasedDashboard(
                user_info=user_info,
                auth_manager=self.auth_manager,  # 传入auth_manager而不是backend
                login_window=self
            )
            self.dashboard.show()
            self.hide()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载界面失败: {str(e)}")
            print(f"错误详情: {traceback.format_exc()}")
            self.show()